package com.wdb007.venus.web.api.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wdb007.venus.svc.biz.utils.DateFormatUtil;
import com.wdb007.venus.svc.facade.BookShelfService;
import com.wdb007.venus.svc.facade.BookgridService;
import com.wdb007.venus.svc.facade.OrderService;
import com.wdb007.venus.svc.facade.UserService;
import com.wdb007.venus.svc.facade.WxAPPMessagePushService;
import com.wdb007.venus.svc.facade.banner.model.BannerImgDTO;
import com.wdb007.venus.svc.facade.book.model.BRBookDTO;
import com.wdb007.venus.svc.facade.book.model.BookCommentsAndUser;
import com.wdb007.venus.svc.facade.book.model.BookCommentsAndUserDTO;
import com.wdb007.venus.svc.facade.book.model.BookCommentsInsertDTO;
import com.wdb007.venus.svc.facade.book.model.BookCommentsQueryPageDTO;
import com.wdb007.venus.svc.facade.book.model.BookGridDTO;
import com.wdb007.venus.svc.facade.book.model.BookGridInfo;
import com.wdb007.venus.svc.facade.book.model.BookGridListDTO;
import com.wdb007.venus.svc.facade.book.model.BookGridListRequestModel;
import com.wdb007.venus.svc.facade.book.model.BookGridPageDTO;
import com.wdb007.venus.svc.facade.book.model.BookGridsDTO;
import com.wdb007.venus.svc.facade.book.model.BookQueryDTO;
import com.wdb007.venus.svc.facade.book.model.BookQueryPageDTO;
import com.wdb007.venus.svc.facade.book.model.BookRecommendationInfoDTO;
import com.wdb007.venus.svc.facade.book.model.BookShelfDTO;
import com.wdb007.venus.svc.facade.book.model.BookShelfFavoriteDTO;
import com.wdb007.venus.svc.facade.book.model.BookShelfInfoDTO;
import com.wdb007.venus.svc.facade.book.model.BookShelfPageDTO;
import com.wdb007.venus.svc.facade.book.model.BookTopicalAgeDTO;
import com.wdb007.venus.svc.facade.book.model.BookgridUnlockDTO;
import com.wdb007.venus.svc.facade.book.model.BorrowReturnBookDTO;
import com.wdb007.venus.svc.facade.book.model.BorrowedOrReturnBookDTO;
import com.wdb007.venus.svc.facade.book.model.BorrowedOrReturnBookResultDTO;
import com.wdb007.venus.svc.facade.book.model.BorrowedUserImgUrlDTO;
import com.wdb007.venus.svc.facade.book.model.PutonBook;
import com.wdb007.venus.svc.facade.book.model.PutonBookPageDTO;
import com.wdb007.venus.svc.facade.book.model.ShareBookDTO;
import com.wdb007.venus.svc.facade.book.model.ShelfBookInfoDTO;
import com.wdb007.venus.svc.facade.book.model.ShelfBookQueryDTO;
import com.wdb007.venus.svc.facade.constant.BizConstants;
import com.wdb007.venus.svc.facade.constant.RspCodeEnum;
import com.wdb007.venus.svc.facade.exception.BizException;
import com.wdb007.venus.svc.facade.model.Age;
import com.wdb007.venus.svc.facade.model.BookTag;
import com.wdb007.venus.svc.facade.model.BookTagAgeDTO;
import com.wdb007.venus.svc.facade.model.BookTopical;
import com.wdb007.venus.svc.facade.model.VenusSvcResp;
import com.wdb007.venus.web.api.book.model.BRBookVO;
import com.wdb007.venus.web.api.book.model.BannerImgVO;
import com.wdb007.venus.web.api.book.model.Book;
import com.wdb007.venus.web.api.book.model.BookCommentsAndUserVO;
import com.wdb007.venus.web.api.book.model.BookCommentsInsertRequest;
import com.wdb007.venus.web.api.book.model.BookCommentsPageRequest;
import com.wdb007.venus.web.api.book.model.BookGridListRequest;
import com.wdb007.venus.web.api.book.model.BookGridPageRequest;
import com.wdb007.venus.web.api.book.model.BookGridUnlockVO;
import com.wdb007.venus.web.api.book.model.BookGridVO;
import com.wdb007.venus.web.api.book.model.BookQueryRequest;
import com.wdb007.venus.web.api.book.model.BookRecommendationInfoResponse;
import com.wdb007.venus.web.api.book.model.BookRecommendationInfoVO;
import com.wdb007.venus.web.api.book.model.BookShelfCodePageRequest;
import com.wdb007.venus.web.api.book.model.BookShelfCodeRequest;
import com.wdb007.venus.web.api.book.model.BookShelfFavoriteVO;
import com.wdb007.venus.web.api.book.model.BookShelfInfoRequest;
import com.wdb007.venus.web.api.book.model.BookShelfInfoVO;
import com.wdb007.venus.web.api.book.model.BookShelfLocationVO;
import com.wdb007.venus.web.api.book.model.BookShelfRequest;
import com.wdb007.venus.web.api.book.model.BookTagAgeVO;
import com.wdb007.venus.web.api.book.model.BookTopicalAgeVO;
import com.wdb007.venus.web.api.book.model.BorrowReturnRequest;
import com.wdb007.venus.web.api.book.model.BorrowedUserImgUrlVO;
import com.wdb007.venus.web.api.book.model.PutonBookListVO;
import com.wdb007.venus.web.api.book.model.ShareBookVO;
import com.wdb007.venus.web.api.model.BaseResponse;
import com.wdb007.venus.web.api.user.model.UserRequest;

@Controller
@RequestMapping("/bookgrid/")
public class BookgridController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger(BookgridController.class);
	
	@Autowired
	private BookgridService bookgridService ;
	@Autowired
	private UserService userService ;
	@Autowired
	private BookShelfService bookShelfService;
	@Autowired
	private WxAPPMessagePushService wxAPPMessagePushService;
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value = "/borrowreturnv2", method = RequestMethod.GET)
	@ResponseBody
	public BaseResponse getBorrowReturnV2(BorrowReturnRequest request) {
		long startTime = System.currentTimeMillis();
		logger.info("获取用户借还书列表getBorrowReturn's request: {}" , JSON.toJSONString(request));
		BaseResponse response = success();
		//查询出借还书整体信息
		BorrowReturnBookDTO brBookDTO = new BorrowReturnBookDTO();
		brBookDTO.setGridCode(request.getGrid_code());
		brBookDTO.setUserId(request.getUserid());
		try {
			BorrowedOrReturnBookResultDTO resultDTO = bookgridService.getBrListV2(brBookDTO);
			Map<String, Object> result = new HashMap<String,Object>();
			List<BRBookVO> list = new ArrayList<BRBookVO>();
			int borrowCount = 0;
			int returnCount = 0;
			BigDecimal transAmount = null;
			if(resultDTO != null) {
				borrowCount = resultDTO.getBorrowCount();
				returnCount = resultDTO.getReturnCount();
				transAmount = resultDTO.getTransAmount();
				List<BorrowedOrReturnBookDTO> bookList = resultDTO.getList();
				for(int i= 0; i<bookList.size();i++) {
					BorrowedOrReturnBookDTO dto = bookList.get(i);
					BRBookVO returnvo = new BRBookVO();
					BeanUtils.copyProperties(dto, returnvo);
					list.add(returnvo);
				}
			}
			if(0 != borrowCount) {
				String tip = bookgridService.getOverQuotaTip(request.getUserid());
				result.put("tip", tip);
			}
			
			result.put("borrowCount", borrowCount);
			result.put("returnCount", returnCount);
			result.put("transAmount", transAmount);
			if(returnCount > 0) {
				result.put("drawTip", bookgridService.isShowDrawTip(request.getUserid()));
			}
			
			result.put("list", list);
			if(borrowCount > 0 || returnCount > 0) {
				logger.info("borrowreturnv2 用户{},推送信息",request.getUserid());
				try {
				String tempId = "QTOz9ne2N22gRllwEbvG43DmKy7gyk4bwSOzo5IT7LE";
				Map<String, Object> content = new HashMap<>();
				String value1 = "";//借阅书籍
				String value2 = "";//归还书籍
				for(BRBookVO vo : list) {
					if((vo.getType()+"").startsWith("2")) {//以2开头为还书
						value2 += "《"+vo.getBookname()+"》 ";
					}else {
						value1 += "《"+vo.getBookname()+"》 ";
					}
				}
				Map<String, Object> keyword1 = new HashMap<>();//申请时间
				keyword1.put("value", DateFormatUtil.formatDate2(new Date()));//
				Map<String, Object> keyword2 = new HashMap<>();//归还书籍
				keyword2.put("value", value2);
				Map<String, Object> keyword3 = new HashMap<>();//借阅书籍
				keyword3.put("value", value1);
				Map<String, Object> keyword4 = new HashMap<>();//借阅费用
				keyword4.put("value", "￥"+transAmount);
				Map<String, Object> keyword5 = new HashMap<>();//备注
				keyword5.put("value", "借阅"+borrowCount+"本，归还"+returnCount+"本");
				
				content.put("keyword1", keyword1);
				content.put("keyword2", keyword2);
				content.put("keyword3", keyword3);
				content.put("keyword4", keyword4);
				content.put("keyword5", keyword5);
				wxAPPMessagePushService.sendContent(tempId, content, request.getUserid(), null, BizConstants.BOOK_BORROW_STATUS_PAGE);
				
				logger.info("borrowreturnv2 用户{},推送信息结束",request.getUserid());
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
			response.setDetail(result);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("debugapi 获取用户借还书列表getBorrowReturn's :执行时间{}ms userId{} response:{}" , (System.currentTimeMillis()-startTime), request.getUserid(), JSON.toJSONString(response));
		return response;
	}
	
	/**
	 * APP通知后端，要打开书格的方法
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/unlock" , method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse unlock(BorrowReturnRequest request) {
		long startTime = System.currentTimeMillis();

		logger.info("App通知后端进行开门  请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			checkIsNull(request.getGrid_code(), "grid_code");
			//1.判断用户是否被锁定
			boolean locked = userService.isLocked(request.getUserid());
			if(locked) {
				throw new BizException(RspCodeEnum.USER_IS_LOCKED);
			}
			//4.需要判断正在扫描的书柜和当前经纬度距离是否小于100米, 后续会增加蓝牙模块来控制
			//5.当前用户是否正在开柜
//			boolean underOpening = bookgridService.isUnderOpening(request.getUserid(), BizConstants.GRID_TRANS_USER_TYPE_0);
			boolean underOpening = bookgridService.isUnderOpening(request.getUserid(), null);
			if(underOpening) {
				throw new BizException(RspCodeEnum.USER_IS_OPENING_GRID);
			}
			//8.判断书柜是否正常，包含书柜是否可用，以及是否已报修
			VenusSvcResp<Boolean> shelfNormalResp = bookgridService.isBookShelfNormal(request.getGrid_code());
			if(null != shelfNormalResp.getRspCodeEnum()) {
				throw new BizException(shelfNormalResp.getRspCodeEnum());
			}
			//查询书柜目前是否有人操作
			String shelfCode = request.getGrid_code().substring(0, 10);
			bookgridService.shelfIsOpened(shelfCode);
			
			BookgridUnlockDTO unlockDTO = new BookgridUnlockDTO();
			unlockDTO.setUserid(request.getUserid());
			unlockDTO.setToken(request.getUsertoken());
			unlockDTO.setGridCode(request.getGrid_code());
//			unlockDTO.setUserType(0);
			BookgridUnlockDTO result = bookgridService.unlock(unlockDTO);
			logger.info("书格 {} 目前的状态为 {}", request.getGrid_code(), result.getStatus());
			switch (result.getStatus()) {
			case "0":
				break;
			case "1":	//书格不存在
				response.setResult(0);
				response.setCode(RspCodeEnum.BOOK_GRID_IS_NOT_EXISTS.getRspCode());
				response.setMessage(RspCodeEnum.BOOK_GRID_IS_NOT_EXISTS.getRspMsg());
				break;
			case "2":	//书格处于报修状态
				response.setResult(0);
				response.setCode(RspCodeEnum.BOOK_GRID_IS_UNDER_DAMAGE.getRspCode());
				response.setMessage(RspCodeEnum.BOOK_GRID_IS_UNDER_DAMAGE.getRspMsg());
				break;
			case "3":	//书格处于未关闭状态
				response.setResult(0);
				response.setCode(RspCodeEnum.BOOK_GRID_IS_UNDER_NON_CLOSED.getRspCode());
				response.setMessage(RspCodeEnum.BOOK_GRID_IS_UNDER_NON_CLOSED.getRspMsg());
				break;
			case "4":	//书格处于不可用状态 available = 0
				response.setResult(0);
				response.setCode(RspCodeEnum.BOOK_GRID_IS_UNAVAILABLE.getRspCode());
				response.setMessage(RspCodeEnum.BOOK_GRID_IS_UNAVAILABLE.getRspMsg());
				break;
			default:
				break;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("debugapi App通知后端进行开门  : 执行时间{}ms userId:{}, response:{}", System.currentTimeMillis()-startTime, request.getUserid(),JSON.toJSONString(response));
		return response ;
	}
	/**
	 * 查询书格状态
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/queryStatus", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryStatus(BorrowReturnRequest request) {
		long startTime = System.currentTimeMillis();
		logger.info("App查询书柜状态queryStatus 请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			checkIsNull(request.getGrid_code(), "grid_code");
			Integer lockStatus = bookgridService.queryStatus(request.getGrid_code());
			BookGridUnlockVO vo = new BookGridUnlockVO();
			vo.setGrid_code(request.getGrid_code());
			vo.setStatus(lockStatus);
			if(1 == lockStatus) {
				vo.setTimestamp((new Date()).getTime());
				Integer remainSeconds = bookgridService.queryRemainingSeconds(request.getGrid_code(), request.getUserid());
				vo.setRemainseconds(remainSeconds);
			}
			response.setDetail(vo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("debugapi App查询书柜状态queryStatus 执行时间{}ms userId:{},response:{}", System.currentTimeMillis()-startTime,request.getUserid(), JSON.toJSONString(response));
		return response ;
	}
	
	@RequestMapping(value="/inventory", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse inventory(UserRequest request) {
		long startTime = System.currentTimeMillis();
		logger.info("App通知再次盘点inventory 请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			VenusSvcResp<Object> venusResp = bookgridService.notifyInventory(request.getUserid());
			if(venusResp.getRspCodeEnum() != null) {
				throw new BizException(venusResp.getRspCodeEnum());
			}
		} catch (Exception e) {
			response = failed(e);
			logger.error(e.getMessage(), e);
		}
		logger.info("debugapi App通知再次盘点inventory 执行时间{}ms userId:{}response:{}", System.currentTimeMillis()-startTime, request.getUserid(), JSON.toJSONString(response));
		return response ;
	}
	
	@RequestMapping(value="/queryPutonList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryPutonList(BookShelfCodePageRequest request) {
		logger.info("新书上架列表查询queryPutonList请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			checkIsNull(request.getShelf_code(), "shelf_code");
			PutonBookPageDTO pageDTO = new PutonBookPageDTO();
			pageDTO.setUserid(request.getUserid());
			pageDTO.setPagesize(request.getPagesize());
			pageDTO.setOffset((request.getPageno()-1)* request.getPagesize());
			pageDTO.setShelfCode(request.getShelf_code());
			
			PutonBook putonBook = bookgridService.getPutonBookList(pageDTO);
			PutonBookListVO vo = new PutonBookListVO();
			vo.setBookcount(putonBook.getBookcount());
			vo.setUpdatedate(putonBook.getUpdatedate());
			for(BRBookDTO dto : putonBook.getBooks()) {
				BRBookVO bookVo = new BRBookVO();
				bookVo.setBookname(dto.getBookname());
				bookVo.setIsbn(dto.getIsbn());
				bookVo.setImgurl(dto.getImgurl());
				vo.getBooks().add(bookVo);
			}
			response.setDetail(vo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("新书上架列表查询queryPutonList响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryTagAgeList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryTagAgeList() {
		logger.info("获取年龄段和标签接口queryTagAgeList请求");
		BaseResponse response = success();
		try {
			BookTagAgeDTO bookTagAgeDTO = bookgridService.queryTagAgeList();
			BookTagAgeVO bookTagAgeVO = new BookTagAgeVO();
			for(Age age :bookTagAgeDTO.getAges()) {
				com.wdb007.venus.web.api.book.model.Age ageVo = new com.wdb007.venus.web.api.book.model.Age();
				ageVo.setAge(age.getAge());
				ageVo.setReadable(age.getReadable());
				bookTagAgeVO.getAges().add(ageVo);
			}
			
			for(BookTag bookTag : bookTagAgeDTO.getTags()) {
				com.wdb007.venus.web.api.book.model.BookTag bookTagVo = new com.wdb007.venus.web.api.book.model.BookTag();
				bookTagVo.setTag_code(bookTag.getTag_code());
				bookTagVo.setTag_name(bookTag.getTag_name());
				bookTagAgeVO.getTags().add(bookTagVo);
			}
			response.setDetail(bookTagAgeVO);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("\"获取年龄段和标签接口queryTagAgeList响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryBookList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryBookList(BookQueryRequest request) {
		logger.info("选择图书列表queryBookList请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			checkIsNull(request.getShelf_code(), "shelf_code");
			BookQueryPageDTO bookQueryPageDTO = new BookQueryPageDTO();
			bookQueryPageDTO.setUserid(request.getUserid());
			bookQueryPageDTO.setPagesize(request.getPagesize());
			bookQueryPageDTO.setOffset((request.getPageno()-1)* request.getPagesize());
			bookQueryPageDTO.setTag_code(request.getTag_code());
			bookQueryPageDTO.setReadable(request.getReadable());
			bookQueryPageDTO.setShelf_code(request.getShelf_code());
			BookQueryDTO bookQueryDTO = bookgridService.queryBookList(bookQueryPageDTO);
			response.setTotalcount(bookQueryDTO.getTotalcount());
			
			List<Book> list = new ArrayList<Book>();
			for(BRBookDTO bookDTO : bookQueryDTO.getList()) {
				Book book = new Book(bookDTO.getIsbn(), bookDTO.getBookname(), bookDTO.getImgurl());
				list.add(book);
			}
			response.setItems(list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("选择图书列表queryBookList响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryGridList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryGridList(BookShelfCodeRequest request) {
		long startTime = System.currentTimeMillis();

		logger.info("获取书柜书格号列表queryGridList请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			checkIsNull(request.getShelf_code(), "shelf_code");
			String shelfCode = request.getShelf_code();
			BookGridListDTO listDTO = bookgridService.queryGridList(shelfCode);
			response.setTotalcount(listDTO.getTotalcount());
			List<BookGridVO> list = new ArrayList<BookGridVO>();
			for(BookGridDTO bookGridDTO : listDTO.getGrids()) {
				BookGridVO vo = new BookGridVO();
				vo.setGrid_code(bookGridDTO.getGrid_code());
				vo.setGrid_name(bookGridDTO.getGrid_name());
				list.add(vo);
			}
			response.setItems(list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("获取书柜书格号列表queryGridList响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	
	@RequestMapping(value="/queryGridBooks", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryGridBooks(BookGridPageRequest request){
		logger.info("获取书柜图书列表queryGridBooks请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			checkIsNull(request.getGrid_code(), "grid_code");
			BookGridPageDTO pageDTO = new BookGridPageDTO();
			pageDTO.setUserid(request.getUserid());
			pageDTO.setPagesize(request.getPagesize());
			pageDTO.setOffset((request.getPageno()-1)* request.getPagesize());
			pageDTO.setGridCode(request.getGrid_code());
			PutonBook putonBook = bookgridService.queryGridBooks(pageDTO);
			response.setTotalcount(putonBook.getBookcount());
			List<Book> list = new ArrayList<Book>();
			for(BRBookDTO bookDTO : putonBook.getBooks()) {
				Book book = new Book(bookDTO.getIsbn(), bookDTO.getBookname(), bookDTO.getImgurl());
				list.add(book);
			}
			response.setItems(list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("获取书柜图书列表queryGridBooks响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryBookInfo", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryBookInfo(BookShelfInfoRequest request) {
		logger.info("获取图书详细信息queryBookInfo请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			checkIsNull(request.getIsbn(), "isbn");
			ShelfBookInfoDTO requestDTO = new ShelfBookInfoDTO();
			BeanUtils.copyProperties(request, requestDTO);
			BookShelfInfoDTO infoDTO = bookgridService.queryBookInfo(requestDTO);
			BookShelfInfoVO vo = new BookShelfInfoVO();
			BeanUtils.copyProperties(infoDTO, vo);
			response.setDetail(vo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("获取图书详细信息queryBookInfo响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryBookRank", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryBookRank(BookShelfCodePageRequest request) {
		logger.info("图书借阅排行queryBookRank请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			checkIsNull(request.getShelf_code(),"shelf_code");
			PutonBookPageDTO pageDTO = new PutonBookPageDTO();
			pageDTO.setUserid(request.getUserid());
			pageDTO.setPagesize(request.getPagesize());
			pageDTO.setOffset((request.getPageno()-1)* request.getPagesize());
			pageDTO.setShelfCode(request.getShelf_code());
			
			PutonBook putonBook = bookgridService.getRankBookList(pageDTO);
			response.setTotalcount(putonBook.getBookcount());
			List<BRBookVO> bookList = new ArrayList<BRBookVO>();
			
			for(BRBookDTO dto : putonBook.getBooks()) {
				BRBookVO bookVo = new BRBookVO();
				bookVo.setBookname(dto.getBookname());
				bookVo.setIsbn(dto.getIsbn());
				bookVo.setImgurl(dto.getImgurl());
				bookList.add(bookVo);
			}
			response.setItems(bookList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("图书借阅排行queryBookRank响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/getHomePage", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getHomePage(BookShelfRequest request) {
		long startTime = System.currentTimeMillis();
		logger.info("手机APP首页getHomePage请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			//1.获得最近的一个书柜信息
			BookShelfDTO reqParam = new BookShelfDTO();
			reqParam.setLatitude(request.getUser_latitude());
			reqParam.setLongitude(request.getUser_longitude());
			Integer mapType  = request.getMap_type();
			reqParam.setCode(request.getShelf_code());
			BookShelfDTO dto = bookShelfService.getNearest(reqParam, mapType);
			//2.获取最新的banner列表
			List<BannerImgDTO> bannerList = bookShelfService.getBannerImgList();
			//3.按照借阅度，来查找5条图书信息
			BookQueryPageDTO bookQueryPageDTO = new BookQueryPageDTO();
			if(request.getPagesize() == 0 && request.getPageno() == 0) {
				bookQueryPageDTO.setPagesize(10);
				bookQueryPageDTO.setOffset(0);
			}else {
				bookQueryPageDTO.setPagesize(request.getPagesize());
				bookQueryPageDTO.setOffset((request.getPageno()-1)* request.getPagesize());
				
			}
			bookQueryPageDTO.setShelf_code(dto.getCode());
			List<BookRecommendationInfoDTO> dtoList = bookgridService.queryBookBorrowCountAndRecommendation(bookQueryPageDTO);
			
			BookRecommendationInfoResponse res = new BookRecommendationInfoResponse();
			List<BannerImgVO> bannerImgVoList = new ArrayList<BannerImgVO>(bannerList.size());
			for(BannerImgDTO bannerImgDTO : bannerList) {
				BannerImgVO bannerImgVo = new BannerImgVO();
				BeanUtils.copyProperties(bannerImgDTO, bannerImgVo);
				bannerImgVo.setBannertype(bannerImgDTO.getBannerType());
				bannerImgVo.setBannerurl(bannerImgDTO.getImgurl());
				bannerImgVoList.add(bannerImgVo);
			}
			res.setBanners(bannerImgVoList);
			res.setBookshelf_code(dto.getCode());
			res.setBookshelf_location(dto.getAddress());
			res.setCol_count(dto.getColCount());
			res.setRow_count(dto.getRowCount());
			res.setLatitude(dto.getLatitude());
			res.setLongitude(dto.getLongitude());
			
			List<BookRecommendationInfoVO> voList = new ArrayList<BookRecommendationInfoVO>();
			if(null != dtoList) {
				for(BookRecommendationInfoDTO infoDTO : dtoList) {
					BookRecommendationInfoVO vo = new BookRecommendationInfoVO();
					BeanUtils.copyProperties(infoDTO, vo);
					vo.setIsbn(infoDTO.getIsbnNo());
					vo.setBookname(infoDTO.getBookName());
					vo.setBorrow_count(infoDTO.getBorrowCount());
					voList.add(vo);
				}
			}
			res.setBooks(voList);
			response.setDetail(res);
		}catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("debugapi 手机APP首页getHomePage响应:耗时{}ms {}", System.currentTimeMillis()-startTime, JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryTopicalAgeList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryTopicalAgeList() {
		long startTime = System.currentTimeMillis();

		logger.info("获取年龄段和主题接口queryTopicalAgeList请求参数");
		BaseResponse response = success();
		try {
			BookTopicalAgeDTO ageDTO = bookgridService.queryTopicalAgeList();
			
			BookTopicalAgeVO bookTopicalAgeVo = new BookTopicalAgeVO();
			for(Age age :ageDTO.getAges()) {
				com.wdb007.venus.web.api.book.model.Age ageVo = new com.wdb007.venus.web.api.book.model.Age();
				ageVo.setAge(age.getAge());
				ageVo.setReadable(age.getReadable());
				bookTopicalAgeVo.getAges().add(ageVo);
			}
			
			for(BookTopical bookTopical : ageDTO.getTopicals()) {
				com.wdb007.venus.web.api.book.model.BookTopical bookTopicalVo = new com.wdb007.venus.web.api.book.model.BookTopical();
				bookTopicalVo.setTopical_code(bookTopical.getTopical_code());
				bookTopicalVo.setTopical_name(bookTopical.getTopical_name());
				bookTopicalAgeVo.getTopicals().add(bookTopicalVo);
			}
			response.setDetail(bookTopicalAgeVo);
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("获取年龄段和主题接口queryTopicalAgeList响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryShelfBookList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryShelfBookList(BookQueryRequest request) {
		long startTime = System.currentTimeMillis();

		logger.info("书库图书列表查询接口queryShelfBookList请求参数:{}", JSON.toJSONString(request));
		BaseResponse response = success();
		
		try {
			checkIsNull(request.getShelf_code(),"shelf_code");
			BookQueryPageDTO bookQueryPageDTO = new BookQueryPageDTO();
			bookQueryPageDTO.setUserid(request.getUserid());
			bookQueryPageDTO.setPagesize(request.getPagesize());
			bookQueryPageDTO.setOffset((request.getPageno()-1)* request.getPagesize());
			bookQueryPageDTO.setTag_code(request.getTag_code());
			if(null != request.getReadable() && !"".equals(request.getReadable())) {
				bookQueryPageDTO.setReadable(request.getReadable());
			}
			bookQueryPageDTO.setShelf_code(request.getShelf_code());
			if(null != request.getTopical_code() && !"0000".equals(request.getTopical_code())) {
				bookQueryPageDTO.setTopical_code(request.getTopical_code());
			}
			bookQueryPageDTO.setSort_by(request.getSort_by());
			ShelfBookQueryDTO bookQueryDTO = bookgridService.queryShelfBookList(bookQueryPageDTO);
			List<BookRecommendationInfoVO> voList = new ArrayList<BookRecommendationInfoVO>();
			for(BookRecommendationInfoDTO infoDTO : bookQueryDTO.getDtoList()) {
				BookRecommendationInfoVO vo = new BookRecommendationInfoVO();
				BeanUtils.copyProperties(infoDTO, vo);
				vo.setBookname(infoDTO.getBookName());
				vo.setIsbn(infoDTO.getIsbnNo());
				vo.setBorrow_count(infoDTO.getBorrowCount());
				voList.add(vo);
			}
			response.setTotalcount(bookQueryDTO.getTotalcount());
			response.setItems(voList);
		} catch (BizException e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
//		logger.info("书库图书列表查询接口queryShelfBookList响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryBorrowedUser", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryBorrowedUser(BookShelfInfoRequest request) {
		long startTime = System.currentTimeMillis();

		logger.info("图书借阅用户接口queryBorrowedUser请求参数:{}", JSON.toJSONString(request));
		BaseResponse response = success();
		
		try {
//			checkIsNull(request.getShelf_code(),"shelf_code");
			checkIsNull(request.getIsbn(), "isbn");
			BorrowedUserImgUrlDTO borrowedUserImgUrl = bookgridService.getBorrowedUserImgUrl(request.getIsbn());
			
			response.setTotalcount(borrowedUserImgUrl.getTotalcount());
			
			List<BorrowedUserImgUrlVO> list = new ArrayList<BorrowedUserImgUrlVO>();
			for(String url : borrowedUserImgUrl.getUrls()) {
				BorrowedUserImgUrlVO vo = new BorrowedUserImgUrlVO();
				vo.setImgurl(url);
				list.add(vo);
			}
			response.setItems(list);
		} catch (BizException e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("图书借阅用户接口queryBorrowedUser响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryComments", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryComments(BookCommentsPageRequest request) {
		logger.info("图书评论列表接口queryComments请求参数:{}", JSON.toJSONString(request));
		BaseResponse response = success();
		
		BookCommentsQueryPageDTO pageDTO = new BookCommentsQueryPageDTO();
		
		try {
			checkIsNull(request.getIsbn(), "isbn");
			pageDTO.setIsbn(request.getIsbn());
			pageDTO.setPagesize(request.getPagesize());
			pageDTO.setOffset((request.getPageno()-1)* request.getPagesize());
			BookCommentsAndUserDTO dto = bookgridService.queryComments(pageDTO);
			response.setTotalcount(dto.getTotalcount());
			List<BookCommentsAndUserVO> list = new ArrayList<BookCommentsAndUserVO>();
			for(BookCommentsAndUser comments: dto.getList()) {
				BookCommentsAndUserVO vo = new BookCommentsAndUserVO();
				BeanUtils.copyProperties(comments, vo);
				list.add(vo);
			}
			response.setItems(list);
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		
		logger.info("图书评论列表接口queryComments响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryMapShelfBook", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryMapShelfBook(BookShelfCodeRequest request) {
		logger.info("地图书柜数据queryMapShelfBook请求参数:{}", JSON.toJSONString(request));
		BaseResponse response = success();
		
		String shelfCode = request.getShelf_code();
		Long userId = request.getUserid();
		
		try {
			checkIsNull(request.getShelf_code(),"shelf_code");
			BookShelfFavoriteDTO favoriteDTO = bookgridService.queryMapShelfBook(shelfCode, userId);
			BookShelfFavoriteVO favoriteVO = new BookShelfFavoriteVO();
			BeanUtils.copyProperties(favoriteDTO, favoriteVO);
			response.setDetail(favoriteVO);
		} catch (BizException e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("地图书柜数据queryMapShelfBook响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/saveBookComments", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse saveBookComments(BookCommentsInsertRequest request) {
		logger.info("图书评论录入saveBookComments请求参数:{}", JSON.toJSONString(request));
		BaseResponse response = success();
		
		try {
			checkIsNull(request.getIsbn(),"isbn");
			checkIsNull(request.getComments(),"comments");
			BookCommentsInsertDTO insertDTO = new BookCommentsInsertDTO();
			insertDTO.setUserId(request.getUserid());
			insertDTO.setComments(request.getComments());
			insertDTO.setIsbn(request.getIsbn());
			bookgridService.saveBookComments(insertDTO);
		} catch (BizException e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("图书评论录入saveBookComments响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/getGridList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getGridList(BookGridListRequest request) {
		
		logger.info("选柜门接口getGridList请求参数:{}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			
			checkIsNull(request.getShelf_code(), "shelf_code");
			checkIsNull(request.getIsbn_list(), "isbn_list");
			JSONArray jsonArr = (JSONArray) JSONArray.parse(request.getIsbn_list());
			Object[] objArr = jsonArr.toArray();
			String[] arr = new String[objArr.length];
			for(int i=0; i<objArr.length; i++) {
				arr[i] = (String)objArr[i];
			}
			BookGridListRequestModel requestModel = new BookGridListRequestModel();
			requestModel.setShelfCode(request.getShelf_code());
			requestModel.setIsbnList(arr);
			BookGridsDTO dto = bookgridService.getGridList(requestModel);
			response.setTotalcount(dto.getTotalcount());
			List<BookGridInfo> infoList = dto.getList();
			List<com.wdb007.venus.web.api.book.model.BookGridInfo> list = new ArrayList<com.wdb007.venus.web.api.book.model.BookGridInfo>(infoList.size());
			for(BookGridInfo info : infoList) {
				com.wdb007.venus.web.api.book.model.BookGridInfo infoVo = new com.wdb007.venus.web.api.book.model.BookGridInfo();
//				BeanUtils.copyProperties(info, infoVo);
				infoVo.setBookgrid_code(info.getBookgrid_code());
				infoVo.setFavorite_count(info.getFavorite_count());
				infoVo.setStored_count(info.getStored_count());
				infoVo.setIsbn_list(info.getIsbn_list());
				infoVo.setBookgrid_img(info.getBookgrid_img());
				infoVo.setDamage_flag(info.getDamage_flag());
				list.add(infoVo);
			}
			response.setItems(list);
			String model = bookShelfService.getModel(request.getShelf_code());
			Map<String, String> map = new HashMap<String, String>();
			map.put("model", model);
			response.setDetail(map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("选柜门接口getGridList响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/unlockOvertime", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse unlockOvertime(UserRequest request) {
		logger.info("开门超时调用接口unlockOvertime请求参数:{}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			//FIXME
			bookgridService.unlockOvertime(request.getUserid());
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("开门超时调用接口unlockOvertime响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/shareBook", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse shareBook(String isbn, Long userid) {
		logger.info("新书分享接口shareBook请求参数:{}", isbn);
		BaseResponse response = success();
		
		try {
			checkIsNull(isbn, "isbn");
			
			ShareBookDTO dto = bookgridService.shareBook(isbn, userid);
			ShareBookVO vo = new ShareBookVO();
			BeanUtils.copyProperties(dto, vo);
			response.setDetail(vo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("新书分享接口shareBook请求参数响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryNearestShelf", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryNearestShelf(BookShelfRequest request) {
		logger.info("获取最近的一个书柜queryNearestShelf 请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		
		try {
			checkIsNull(request.getUser_longitude(), "user_longitude");
			checkIsNull(request.getUser_latitude(), "user_latitude");
			checkIsNull(request.getMap_type(), "map_type");
			
			//1.获得最近的一个书柜信息
			BookShelfDTO reqParam = new BookShelfDTO();
			reqParam.setLatitude(request.getUser_latitude());
			reqParam.setLongitude(request.getUser_longitude());
			Integer mapType  = request.getMap_type();
			reqParam.setCode(request.getShelf_code());
			BookShelfDTO dto = bookShelfService.getNearest(reqParam, mapType);
			BookShelfLocationVO vo = new BookShelfLocationVO();
			vo.setBookshelf_code(dto.getCode());
			vo.setArea(dto.getArea());
			vo.setAddress(dto.getAddress());
			vo.setLatitude(dto.getLatitude());
			vo.setLongitude(dto.getLongitude());
			response.setDetail(vo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("获取最近的一个书柜queryNearestShelf 响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/getShelfInfo", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getShelfInfo(String bookshelf_code) {
		logger.info("获取书柜信息getShelfInfo's请求参数: {}", bookshelf_code);
		BaseResponse response = success();
		
		try {
			checkIsNull(bookshelf_code, "bookshelf_code");
			BookShelfDTO bookShelf = bookShelfService.get(bookshelf_code);
			
			BookShelfLocationVO vo = new BookShelfLocationVO();
			vo.setAddress(bookShelf.getAddress());
			vo.setArea(bookShelf.getArea());
			vo.setLatitude(bookShelf.getLatitude());
			vo.setLongitude(bookShelf.getLongitude());
			vo.setBookshelf_code(bookShelf.getCode());
			response.setDetail(vo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("获取书柜信息getShelfInfo's响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryshelfList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryshelfList(BookShelfRequest request) {
		logger.info("获取书柜列表queryshelfList 请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		
		try {
			checkIsNull(request.getUser_longitude(), "user_longitude");
			checkIsNull(request.getUser_latitude(), "user_latitude");
			checkIsNull(request.getMap_type(), "map_type");
			
			BookShelfDTO reqParam = new BookShelfDTO();
			reqParam.setLatitude(request.getUser_latitude());
			reqParam.setLongitude(request.getUser_longitude());
			Integer mapType  = request.getMap_type();
			reqParam.setCode(request.getShelf_code());
			int pageno = request.getPageno();
			int pagesize = request.getPagesize();
			Integer offset = null;
			if(pagesize != 0 && pageno != 0) {
				offset = (pageno -1) * pagesize;
			}
			BookShelfPageDTO pageDTO = bookShelfService.queryshelfList(reqParam, mapType, offset, pagesize);
			response.setItems(pageDTO.getList());
			response.setTotalcount(pageDTO.getTotalcount());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("获取书柜列表queryshelfList 响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryAppShelfList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryAppShelfList(BookShelfRequest request) {
		logger.info("获取APP地图页面书柜列表queryAppShelfList 请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		
		try {
			checkIsNull(request.getUser_longitude(), "user_longitude");
			checkIsNull(request.getUser_latitude(), "user_latitude");
			checkIsNull(request.getMap_type(), "map_type");
			
			BookShelfDTO reqParam = new BookShelfDTO();
			reqParam.setLatitude(request.getUser_latitude());
			reqParam.setLongitude(request.getUser_longitude());
			Integer mapType  = request.getMap_type();
			reqParam.setCode(request.getShelf_code());
			BookShelfPageDTO pageDTO = bookShelfService.queryshelfList(reqParam, mapType, null, null);
			response.setItems(pageDTO.getList());
			response.setTotalcount(pageDTO.getTotalcount());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("获取APP地图页面书柜列表queryAppShelfList 响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/readStatistics", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse readStatistics() {
		logger.info("readStatistics=============");
		BaseResponse response = success();
		try {
			orderService.readStatistics();
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("readStatistics 响应: {}", JSON.toJSONString(response));
		return response;
	}
}
